//
//  SelectedGoodNewViewController1.m
//  HAODE
//
//  Created by panquan on 16/3/22.
//  Copyright © 2016年 reabam.com. All rights reserved.
//

#import "SelectedGoodNewViewController1.h"
#import "SelectedGoodNewHeaderDataModel.h"
#import "FMDB.h"
#import "PlaceOrderSpecTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "specTableViewDataModel.h"
#import "WhsInAddViewController.h"
#import "OrderExtAddViewController.h"
#import "BusinessCheckVouchContinueViewController.h"
#import "NoSpecFmdbModel.h"
#import "NoSpecFmdbTool.h"
#import "HasSpecFmdbModel.h"
#import "HasSpecFmdbTool.h"
#import "LeftJoinFmdbModel.h"
#import "fmDataModel.h"
#import "SelectedGoodCell.h"
#import "GetAddBuyGoodsViewController.h"
#import "ShopCartSuitsViewController.h"
#import "ReabamSingleton.h"
#import "ShopCartTrunDonationViewController.h"
#import "GatherSingleViewController.h"
#import "SelectedGoodNewHeaderDataModel1.h"

@interface SelectedGoodNewViewController1 ()<PlaceOrderSpecCellDelegate,SelectedGoodCellDelegate,GetAddBuyGoodsViewControllerDelegate,UIGestureRecognizerDelegate,UITableViewDelegate,UITableViewDataSource,ShopCartSuitsViewControllerDelegate,ShopCartTrunDonationViewControllerDelegate>
{
    NSMutableArray *headerModelArray;
    NSMutableArray *headerModelArray1;
    NSMutableArray *isCurrent;
    NSMutableArray *isAvailable;
    NSMutableArray *planId;
    NSMutableArray *sptypeName;
    NSMutableArray *planTitle;
    UIView*modifyThePreferentialView;
    NSString *userToken;
    NSString *isSuitStr;
    NSString *shopCartIdStr;
    NSString *requestSat;
    NSInteger parentTag;
    NSString*tagStr;
    UITableView*table_list;
    NSString*isCurrentPlanId;
    ReabamSingleton*commdity;
    NSUInteger h;
    UIView*operationsView;
    bool saveAccount;
    NSArray*operationsArray;
    NSArray*ColorArray;
    UIView*noDataView;
}
@property (retain, nonatomic) UIAlertView* alt;
@end

@implementation SelectedGoodNewViewController1
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
     commdity=[ReabamSingleton shared];
    self.memberDict=commdity.dataMemberDict;
    if ([self.typeString isEqualToString:@"SCANCASHIER"]) {
        [_submitConfirmBtn setTitle:@"提交确认" forState:UIControlStateNormal];
        
    }
    [self setNavigation];
    [self initDataBase];
}
-(void)viewDidLoad{
    
    [super viewDidLoad];
  
    [self setAutoLayout];
    UIButton* operationsBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 0.0,  60/2, 60/2)];
    [operationsBtn setTitle:@"···" forState:UIControlStateNormal];
    operationsBtn.titleLabel.font=[UIFont systemFontOfSize:28];
    [operationsBtn setTitleColor:shenhuiColor forState:UIControlStateNormal];
    [operationsBtn addTarget:self action:@selector(operations:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* myBtnBtn = [[UIBarButtonItem alloc] initWithCustomView:operationsBtn];
    self.navigationItem.rightBarButtonItem = myBtnBtn;
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    userToken = [user objectForKey:@"tokenId"];

    [_tableView registerClass:[SelectedGoodCell class] forCellReuseIdentifier:@"SelectedGoodNewViewController1"];
    UIView*view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
    _tableView.tableFooterView=view;
}

-(void)operations:(UIButton*)sender{
    saveAccount=!saveAccount;
    if (saveAccount) {
        operationsArray=@[@"转赠品"];
        [self Btn];
    }else{
        
        [operationsView removeFromSuperview];
}
}
-(void)Btn{
    
    operationsView=[[UIView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, 110)];
    operationsView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:operationsView];
    UITapGestureRecognizer *singleFingerOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyBoad)];
    singleFingerOne.numberOfTouchesRequired = 1; //手指数
    singleFingerOne.numberOfTapsRequired = 1; //tap次数
    singleFingerOne.delegate = self;
    [self.view addGestureRecognizer:singleFingerOne];
    ColorArray =[NSArray arrayWithObjects:[UIColor colorWithRed:90/255.0 green:130/255.0 blue:26/255.0 alpha:1.0],nil];
    for (int i = 0; i<operationsArray.count; i++) {
        UIButton *optName = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-168/2*(i+1),0, 168/2, 110)];
        [optName setTitle:operationsArray[i]  forState:UIControlStateNormal];
        optName.tag=i;
        [optName setTitleColor:[UIColor whiteColor] forState:0];
        optName.titleLabel.font=[UIFont systemFontOfSize:13];
        optName.backgroundColor=ColorArray[i];
        [optName addTarget:self action:@selector(btnTouchUpInsid:) forControlEvents:UIControlEventTouchUpInside];
        [operationsView addSubview:optName];
    }
}


-(void)btnTouchUpInsid:(UIButton*)sender{
    [operationsView removeFromSuperview];
        ShopCartTrunDonationViewController *detailViewController = [[ShopCartTrunDonationViewController alloc] init];
    detailViewController.mDelegate=self;
        [self.navigationController pushViewController:detailViewController animated:YES];

}


-(void)update:(NSString *)updateStr{
//    [self initDataBase];

}
-(void)initDataBase
{
    [self getNoSpecDataFromDB];
}
-(void )getNoSpecDataFromDB
{
    headerModelArray=[NSMutableArray array];
    headerModelArray1=[NSMutableArray array];
    [noDataView removeFromSuperview];
      if ([self.typeString isEqualToString:@"SCANCASHIER"]) {
       NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
       [params setObject:userToken forKey:@"tokenId"];
        [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
          if (self.memberDict.count>0) {
              [params setObject:[self.memberDict objectForKey:@"memberId"] forKey:@"memberId"];
          }
//          NSLog(@"Business/ShopCart/Detail******===%@",params);
       [HttpRequest requestData:@"Business/ShopCart/Detail" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
           if (isSuccess) {
               NSLog(@"Business/ShopCart/Detail******===%@",severDataDict.dataDict);
               if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                   [Global hideProgressHUDInternal:self.view];
                   _Dict=severDataDict.dataDict;
                   _titleLabel.text=[NSString stringWithFormat:@"已选%d件商品",[[severDataDict.dataDict objectForKey:@"totalQty"] intValue]];
                    _totalLabel.text=[NSString stringWithFormat:@"%.2f",[[severDataDict.dataDict objectForKey:@"ySelRealMoney"]doubleValue]];
                   _totalPromotionMoney.text=[NSString stringWithFormat:@"总额￥%.2f  已减￥%.2f",[[severDataDict.dataDict objectForKey:@"totalMoney"]doubleValue],[[severDataDict.dataDict objectForKey:@"totalPromotionMoney"]doubleValue]];
                   NSMutableArray *mArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                   
                   NSLog(@"Business/ShopCart/Detail******===%ld",mArray.count);

                   
                   if (mArray.count>0) {
                       
                  
                   for (NSDictionary* dicc in mArray )
                   {
                        SelectedGoodNewHeaderDataModel1 *model1=[SelectedGoodNewHeaderDataModel1 mj_objectWithKeyValues:dicc];
                       SelectedGoodNewHeaderDataModel *model=[SelectedGoodNewHeaderDataModel mj_objectWithKeyValues:dicc];
                        [headerModelArray addObject:model];
                       [headerModelArray1 addObject:model1];

                       
                       if (model.combiItems.count>0) {
                           for (NSDictionary* dic in model.combiItems ){
                            SelectedGoodNewHeaderDataModel *model=[SelectedGoodNewHeaderDataModel mj_objectWithKeyValues:dic];
                            SelectedGoodNewHeaderDataModel1 *model1=[SelectedGoodNewHeaderDataModel1 mj_objectWithKeyValues:dic];
                            [headerModelArray addObject:model];
                             [headerModelArray1 addObject:model1];
                           }
                       }
                       
                   }
                   }else{
                       noDataView=[[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight/2-50, ScreenWidth, 80)];
                       [self.view addSubview:noDataView];
                       UIImageView*noImage=[[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-47, 0, 94, 51)];
                       noImage.image=[UIImage imageNamed:@"meiyoushuju"];
                       [noDataView addSubview:noImage];
                       UILabel*noLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,65, ScreenWidth, 14)];
                       noLabel.text=@"没有列表数据，赶紧去添加！";
                       noLabel.textColor=zhonghuiColor; noLabel.font=[UIFont systemFontOfSize:14];
                       noLabel.textAlignment=NSTextAlignmentCenter;
                       [noDataView addSubview:noLabel];
                       
                   }
    
                       
                   [_tableView reloadData];

               }
               else
               {
                   [Global hideProgressHUDInternal:self.view];
                   NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                   [Global showTextHudSub:requestResultStr view:self.view];
                   
               }
               
           }else
           {
               [Global hideProgressHUDInternal:self.view];
               [Global showTextHudSub:severDataDict.resultStr view:self.view];
           }
       }];
       

   
   }else{
    NSString *sqlStr=[NSString stringWithFormat:@"SELECT * FROM t_NoSpec WHERE userToken = '%@' AND typeString = '%@' ;" ,userToken,_typeString];
    NSArray *array=[NoSpecFmdbTool queryData:sqlStr];
    //    NSLog(@"array>>>>--====%@",array);
    for (int i=0;i<array.count;i++) {
        NoSpecFmdbModel *fmModel=array[i];
        SelectedGoodNewHeaderDataModel *model=[[SelectedGoodNewHeaderDataModel alloc] init];
        
        model.imageUrlFull=fmModel.imageUrlFull;
        model.itemCode=fmModel.itemCode;
        model.itemId=fmModel.itemId;
        model.itemName=fmModel.itemName;
        model.maxPrice=fmModel.maxPrice;
        
        model.minPrice=fmModel.minPrice;
        model.salePrice=fmModel.salePrice;
        model.invQty=fmModel.invQty;
        
        model.specType=fmModel.specType;
        model.specCount=fmModel.specCount;
        model.isOpened = NO;
        
        [headerModelArray addObject:model];
         NSLog(@"model.specCount^^^^^===%@",model.specCount);
    }
       
       [_tableView reloadData];

   }
    
}
-(void)ShopCartMerge:(NSString *)pidStr :(NSString *)specIdStr :(NSString *)ySelQty {
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:userToken forKey:@"tokenId"];
   
    [params setValue:ySelQty  forKey:@"quantity"];
    if([[NSString stringWithFormat:@"%@",  requestSat]isEqualToString:@"Modify"]) {
        [params setValue:@"Y" forKey:@"isSelect"];
        [params setValue:shopCartIdStr forKey:@"shopCartId"];
    }else{
        [params setValue:isSuitStr  forKey:@"isSuit"];
        [params setValue:pidStr forKey:@"itemId"];
        [params setValue:specIdStr forKey:@"specId"];
    }
      [params setValue:isCurrentPlanId forKey:@"planId"];
    
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:3 view:self.view];
     NSLog(@"params====%@",params);
    [HttpRequest requestData:[NSString stringWithFormat:@"Business/ShopCart/%@",requestSat] params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                  [Global hideProgressHUDInternal:self.view];
                NSLog(@"SCANrequestItemDetail====%@",severDataDict.dataDict);
                [self getNoSpecDataFromDB];
                }else
            {
                  [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
                
            }
        }
        else
        {
          [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
    }];
    
    
}

-(void)subtractCountBtn:(NSString *)subtractCountBtn :(NSString *)isSuit{
    isSuitStr=isSuit;
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[subtractCountBtn.intValue];
      isCurrentPlanId=headerModel.planId;
    if([[NSString stringWithFormat:@"%@",  headerModel.productType]isEqualToString:@"Gift"]) {
        requestSat=@"Modify";
        shopCartIdStr=headerModel.id;
    }else{
        requestSat=@"Merge";
    }
    if ([isSuitStr isEqualToString:@"Y"]) {
        NSString *oriCount=[NSString stringWithFormat:@"%d",[headerModel.suitQty intValue]];
        oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]-1];
        [self ShopCartMerge:headerModel.itemId :headerModel.specId :oriCount];
    }else{
    
        NSString *oriCount=[NSString stringWithFormat:@"%d",[headerModel.quantity intValue]];
        oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]-1];
        [self ShopCartMerge:headerModel.itemId :headerModel.specId :oriCount];

    }
}
-(void)addCountBtn:(NSString *)addCountBtn :(NSString *)isSuit
{
    isSuitStr=isSuit;
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[addCountBtn.intValue];
    isCurrentPlanId=headerModel.planId;
    if([[NSString stringWithFormat:@"%@",  headerModel.productType]isEqualToString:@"Gift"]) {
    shopCartIdStr=headerModel.id;
    requestSat=@"Modify";
    }else{
    requestSat=@"Merge";
    }
    if ([isSuitStr isEqualToString:@"Y"]) {
        if ([headerModel.suitQty  intValue]<[ headerModel.invQty intValue]) {
            NSString *oriCount=[NSString stringWithFormat:@"%d",[headerModel.suitQty intValue]];
            oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]+1];
            [self ShopCartMerge:headerModel.itemId :headerModel.specId :oriCount];
        }else{
            NSString *oriCount=[NSString stringWithFormat:@"%d",[headerModel.suitQty intValue]];
            oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]+1];
            [self ShopCartMerge:headerModel.itemId :headerModel.specId :oriCount];

            [self showAlertMessage:@"已超出商品库存量"];
        }
    }else{
        
        if ([headerModel.quantity  intValue]<[ headerModel.invQty intValue]) {
            NSString *oriCount=[NSString stringWithFormat:@"%d",[headerModel.quantity intValue]];
            oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]+1];
            [self ShopCartMerge:headerModel.itemId :headerModel.specId :oriCount];
        }else{
            NSString *oriCount=[NSString stringWithFormat:@"%d",[headerModel.quantity intValue]];
            oriCount=[NSString stringWithFormat:@"%d",[oriCount intValue]+1];
            [self ShopCartMerge:headerModel.itemId :headerModel.specId :oriCount];
               [self showAlertMessage:@"已超出商品库存量"];
        }
        
    }
    
}

- (void)modifyTheBtn:(NSString *)modifyTheBtn{
    isCurrent=[NSMutableArray array];
    isAvailable=[NSMutableArray array];
    planId=[NSMutableArray array];
    sptypeName=[NSMutableArray array];
    planTitle=[NSMutableArray array];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.window makeKeyAndVisible];
    modifyThePreferentialView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    modifyThePreferentialView.backgroundColor=[UIColor blackColor];
    modifyThePreferentialView.alpha=0.65;
    [self.window addSubview:modifyThePreferentialView];
    UITapGestureRecognizer *singleFingerOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyBoad)];
        singleFingerOne.numberOfTouchesRequired = 1; //手指数
    singleFingerOne.numberOfTapsRequired = 1; //tap次数
    singleFingerOne.delegate = self;
    [modifyThePreferentialView addGestureRecognizer:singleFingerOne];
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[modifyTheBtn.intValue];
    NSMutableArray* arr=[[NSMutableArray alloc]init];
    arr=headerModel.plans;
    
    for (NSDictionary* dicc in arr )
    {
        [isAvailable addObject:[dicc valueForKey:@"isAvailable"]];
        [isCurrent addObject:[dicc valueForKey:@"isCurrent"]];
        [planId addObject:[dicc valueForKey:@"planId"]];
        [planTitle addObject:[dicc valueForKey:@"planTitle"]];
        [sptypeName addObject:[dicc valueForKey:@"sptypeName"]];
        if ([[NSString stringWithFormat:@"%@", [dicc valueForKey:@"isAvailable"]]isEqualToString:@"Y"]&&[[NSString stringWithFormat:@"%@",[dicc valueForKey:@"isCurrent"]]isEqualToString:@"Y"]) {
            
            isCurrentPlanId=[NSString stringWithFormat:@"%@",[dicc valueForKey:@"planId"]];
        }
    }

    UIView*view=[[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight-500, ScreenWidth, 500)];
    view.backgroundColor=[UIColor whiteColor];
    [self.window addSubview:view];
    UILabel*conditionsContenLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 30, ScreenWidth, 18)];
    [conditionsContenLabel setText:[NSString stringWithFormat:@"%@",@"修改优惠"]];
    conditionsContenLabel.font=[UIFont systemFontOfSize:17];
    conditionsContenLabel.textColor=[UIColor blackColor];
    conditionsContenLabel.textAlignment=NSTextAlignmentCenter;
    [view addSubview:conditionsContenLabel];
    UILabel*lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(10, 64-0.4, ScreenWidth-20, 0.45)];
    [lineLabel setBackgroundColor:qianhuiColor];
    [view addSubview:lineLabel];
    UIButton*cancelBtn =[[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth-40,-15,30, 30)];
    [cancelBtn setImage:[UIImage imageNamed:@"chas"] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(closeKeyBoad) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:cancelBtn];
    
    table_list = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, 400) style:UITableViewStylePlain];
    
    table_list.delegate = self;
    table_list.dataSource = self;
    table_list.rowHeight = 45;
    table_list.separatorStyle=UITableViewCellSeparatorStyleNone;
    [table_list registerClass:[SelectedGoodCell class] forCellReuseIdentifier:@"SelectedGoodNewViewController1"];

    [view addSubview:table_list];

    [table_list reloadData];
    UIButton* tureBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 500-45, ScreenWidth, 45)];
    [tureBtn setTitle:@"确认" forState:UIControlStateNormal];
    [tureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    tureBtn.backgroundColor=luseColor;
    tureBtn.tag=modifyTheBtn.intValue;
    CGColorSpaceRef tureBTnSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef tureBTncolorref = CGColorCreate(tureBTnSpace,(CGFloat[]){204.0/255.0,153.0/255.0, 51.0/255.0, 1.0});
    [tureBtn.layer setBorderColor:tureBTncolorref];//边框颜色
    [tureBtn addTarget:self action:@selector(ture:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:tureBtn];
  
}
-(void)ture:(UIButton*)sender{

    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[sender.tag];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:userToken forKey:@"tokenId"];
    [params setValue:isCurrentPlanId forKey:@"planId"];
    [params setValue:headerModel.id forKey:@"shopCartId"];
     [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"Business/ShopCart/UpdatePlan" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                
                [self.window makeKeyWindow];
                self.window.hidden=YES;
                [modifyThePreferentialView removeFromSuperview];
                [self getNoSpecDataFromDB];
            }else
            {
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
                
            }
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
    }];

   
}

-(void)closeKeyBoad
{
    [self.window makeKeyWindow];
    self.window.hidden=YES;
    [modifyThePreferentialView removeFromSuperview];
     [operationsView removeFromSuperview];
}
- (void)chooseBtn:(NSString *)chooseBtn :(NSString *)chooseStr{
    if ([chooseStr isEqualToString:@"选择套装"]||[chooseStr isEqualToString:@"重选套装"]){
        
        SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[chooseBtn.intValue];
        ShopCartSuitsViewController *detailViewController = [[ShopCartSuitsViewController alloc] init];
        detailViewController.mDelegate=self;
        detailViewController.chooseStr=chooseStr;
        detailViewController.shopCartId=headerModel.id;
        [self.navigationController pushViewController:detailViewController animated:YES];
        
    }else if ([chooseStr isEqualToString:@"去凑单"]||[chooseStr isEqualToString:@"继续凑单"]){
        
        SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[chooseBtn.intValue];
        GatherSingleViewController *detailViewController = [[GatherSingleViewController alloc] init];
        detailViewController.shopCartId=headerModel.id;
        [self.navigationController pushViewController:detailViewController animated:YES];
        
    }else{
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[chooseBtn.intValue];
    GetAddBuyGoodsViewController *detailViewController = [[GetAddBuyGoodsViewController alloc] init];
    detailViewController.mDelegate=self;
    detailViewController.chooseStr=chooseStr;
    detailViewController.shopCartId=headerModel.id;
    detailViewController.planId=headerModel.planId;
    [self.navigationController pushViewController:detailViewController animated:YES];
    
    }
}

-(void)CountBtn:(NSString *)CountBtn :(NSString *)isSuit{
    isSuitStr=isSuit;
    SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[CountBtn.intValue];
      isCurrentPlanId=headerModel.planId;
    if([[NSString stringWithFormat:@"%@",  headerModel.productType]isEqualToString:@"Gift"]) {
        requestSat=@"Modify";
        shopCartIdStr=headerModel.id;
    }else{
        requestSat=@"Merge";
    }
    UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"数量"
                           
                                                    message:@"请输入修改的数量"
                           
                                                   delegate:self
                           
                                          cancelButtonTitle:@"取消"
                           
                                          otherButtonTitles:@"确定",nil];
    alertView.tag=CountBtn.intValue;
    [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];


    UITextField * text1 = [alertView textFieldAtIndex:0];
    
    if ([self.typeString isEqualToString:@"SCANCASHIER"]) {
        NSString *oriCount=[NSString stringWithFormat:@"%d",[headerModel.quantity intValue]];
        text1.text=oriCount;
    }else{
        NSString *oriCount=[NSString stringWithFormat:@"%d",[headerModel.specCount intValue]];
        text1.text=oriCount;
    }
    tagStr=[NSString stringWithFormat:@"%d",CountBtn.intValue];
    text1.contentVerticalAlignment= UIControlContentVerticalAlignmentCenter;
    text1.keyboardType = UIKeyboardTypeNumberPad;
    [alertView show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==30000) {
        
        if (buttonIndex == 1)
        {
            
           
        
    }else{
        
        if ([self.typeString isEqualToString:@"SCANCASHIER"]) {
            NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
            [params setObject:userToken forKey:@"tokenId"];
            [params setObject:@"Y" forKey:@"isClear"];
            [HttpRequest requestData:@"Business/ShopCart/Remove" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                if (isSuccess) {
                    NSLog(@"******===%@",severDataDict.dataDict);
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                        [Global hideProgressHUDInternal:self.view];
                        
                        [self getNoSpecDataFromDB];
                    }
                    else
                    {
                        [Global hideProgressHUDInternal:self.view];
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        [Global showTextHudSub:requestResultStr view:self.view];
                        
                    }
                    
                }else
                {
                    [Global hideProgressHUDInternal:self.view];
                    [Global showTextHudSub:severDataDict.resultStr view:self.view];
                }
            }];
            
            
            
        }else{
            
            
        }
    }
        
    }else if (alertView.tag==1000000) {
        
       
    }else if (alertView.tag==2000000){
       
        if (buttonIndex == 1)
        {
            
             SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[tagStr.intValue];
            if ([self.typeString isEqualToString:@"SCANCASHIER"]) {
                
                    NSString *oriCount=[NSString stringWithFormat:@"%@",@"0"];
                   [self ShopCartMerge:headerModel.itemId :headerModel.specId :oriCount];
            }        }
    
    }else{
    
if (buttonIndex == 1)
    {
        UITextField * text1 = [alertView textFieldAtIndex:0];
        text1.contentVerticalAlignment= UIControlContentVerticalAlignmentCenter;
        text1.keyboardType = UIKeyboardTypeNumberPad;

        if (text1.text.intValue==0) {
            
            UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"是否确定删除该商品"
                                       
                                                                message:@""
                                       
                                                               delegate:self
                                       
                                                      cancelButtonTitle:@"取消"
                                       
                                                      otherButtonTitles:@"确定",nil];
            alertView.tag=2000000;
            [alertView show];
        }else{

                SelectedGoodNewHeaderDataModel *headerModel=headerModelArray[alertView.tag];
                if ([self.typeString isEqualToString:@"SCANCASHIER"]) {
             if ([text1.text  intValue]<=[headerModel.invQty intValue]) {
                NSString *oriCount=[NSString stringWithFormat:@"%d",[text1.text intValue]];
                    [self ShopCartMerge:headerModel.itemId :headerModel.specId :oriCount];
             }else{
                 [self showAlertMessage:@"已超出商品库存量"];
                 NSString *oriCount=[NSString stringWithFormat:@"%d",[text1.text intValue]];
                 [self ShopCartMerge:headerModel.itemId :headerModel.specId :oriCount];
             }
                
            }}}
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (tableView == _tableView) {
        return headerModelArray.count;
    }
    return planId.count;

    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (tableView == _tableView) {
    SelectedGoodNewHeaderDataModel *weibo = [headerModelArray objectAtIndex:indexPath.row];
    
    return weibo.getWeiboHight+142;
    }else{
        NSString *s2 =[NSString stringWithFormat:@"%@", sptypeName[indexPath.row]];
        UIFont *font2 = [UIFont systemFontOfSize:11];
        CGSize size2 = CGSizeMake(ScreenWidth-60, 2000);
        CGSize labelsize2 = [s2 sizeWithFont:font2 constrainedToSize:size2 lineBreakMode:NSLineBreakByCharWrapping];

        NSString *s =[NSString stringWithFormat:@"%@", planTitle[indexPath.row]];
        UIFont *font = [UIFont systemFontOfSize:14];
        CGSize size = CGSizeMake(ScreenWidth-labelsize2.width-15-50, 2000);
        CGSize labelsize= [s sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping];
        
        h=labelsize.height+30;

    }
    
    return  h;

    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    SelectedGoodCell*cell = [tableView dequeueReusableCellWithIdentifier:@"SelectedGoodNewViewController1"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (tableView == _tableView) {
        
        if (cell == nil) {
            
          
        }else{
        for (UIView *view in [cell subviews]){
            [view removeFromSuperview];
        }
        cell.mDelegate=self;
        cell.GoodsInOrderListModel=headerModelArray[indexPath.row];
        cell.addCountBtn.tag=indexPath.row;
        cell.subtractCountBtn.tag=indexPath.row;
        cell.CountBtn.tag=indexPath.row;
        cell.chooseBtn.tag=indexPath.row;
        cell.chooseBtn1.tag=indexPath.row;
        cell.modifyTheBtn.tag=indexPath.row;
        SelectedGoodNewHeaderDataModel *Model = [headerModelArray objectAtIndex:indexPath.row];
         if (Model.combiItems.count>0) {
             
             
                    cell.lineLabel.hidden=YES;
                    cell.hengxianLine.hidden=NO;
                }else{
                            cell.lineLabel.hidden=NO;
                            cell.hengxianLine.hidden=YES;
             if (headerModelArray.count==indexPath.row+1) {
             
             
             }else{
                            if (indexPath.row>0) {
                                SelectedGoodNewHeaderDataModel *Model = headerModelArray [indexPath.row];

                                SelectedGoodNewHeaderDataModel1 *Model1 = headerModelArray1[indexPath.row+1];
                                NSLog(@"%@=====%@",Model.planId,Model1.planId);
                                if ([Model.planId isEqualToString:Model1.planId]) {

                                    
                                    if ([Model.planType isEqualToString:@"P006"]) {
                                        
                                    }else  if ([Model.planType isEqualToString:@"P003"]) {
                                    
                                    cell.lineLabel.hidden=YES;
                                    cell.hengxianLine.hidden=NO;
                                    }
                                 
                                
                                }else{

                                
                                 
                            }
                               
                            
                            }else{
                                    
                        }
                    
                
                }
            
         }
    }
        
        cell.lineLabel1.hidden=YES;
        
//        if (indexPath.row==0) {
//            cell.lineLabel.hidden=YES;
//            cell.hengxianLine.hidden=YES;
//        }
        if (headerModelArray.count==indexPath.row+1) {

            cell.lineLabel1.hidden=NO;
//
        }
    }
    
    if (tableView == table_list) {

        
        if (cell == nil) {
                }else{
            for (UIView *subView in cell.contentView.subviews)
            {
                [subView removeFromSuperview];
            }  
        }
        
        NSString *s2 =[NSString stringWithFormat:@"%@", sptypeName[indexPath.row]];
        UIFont *font2 = [UIFont systemFontOfSize:11];
        CGSize size2 = CGSizeMake(ScreenWidth-60, 2000);
        CGSize labelsize2 = [s2 sizeWithFont:font2 constrainedToSize:size2 lineBreakMode:NSLineBreakByCharWrapping];
        cell.conditions =[[UILabel alloc]initWithFrame:CGRectMake(15,17, labelsize2.width, 13)];
        cell.conditions.textColor=[UIColor whiteColor];
        [cell.conditions.layer setCornerRadius:0.5];
        [cell.conditions.layer setBorderWidth:0.5];
        [cell.conditions.layer setMasksToBounds:YES];
        CGColorSpaceRef colorSpace12 = CGColorSpaceCreateDeviceRGB();
        CGColorRef colorref12 = CGColorCreate(colorSpace12,(CGFloat[]){ 252/255.0, 54/255.0, 30/255.0, 1.0 });
        [cell.conditions.layer setBorderColor:colorref12];//边框颜色
        cell.conditions.font=[UIFont systemFontOfSize:10];
        cell.conditions.text=sptypeName[indexPath.row];
        cell.conditions.textAlignment=NSTextAlignmentCenter;
        cell.conditions.backgroundColor=[UIColor redColor];
        [cell.contentView addSubview:cell.conditions];
       
        
        NSString *s =[NSString stringWithFormat:@"%@", planTitle[indexPath.row]];
        UIFont *font = [UIFont systemFontOfSize:14];
        CGSize size = CGSizeMake(ScreenWidth-labelsize2.width-15-50, 2000);
        CGSize labelsize= [s sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping];
        
        cell.conditionsLabel = [[UILabel alloc]initWithFrame:CGRectMake(cell.conditions.right+5,0, ScreenWidth-labelsize2.width-15-50, labelsize.height+30)];
                    cell.conditionsLabel.textColor=shenhuiColor;
        cell.conditionsLabel.numberOfLines=0;
        cell.conditionsLabel.text=planTitle[indexPath.row];
        cell.conditionsLabel.font=[UIFont systemFontOfSize:14];
        [cell.contentView addSubview:cell.conditionsLabel];
        
        cell.chooseBtn1=[[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth-40, (labelsize.height+30)/2-15, 30, 30)];
        [cell.chooseBtn1 setUserInteractionEnabled:NO];
        if ([isCurrent[indexPath.row]isEqualToString:@"Y"]) {
            UIImage *img=[UIImage imageNamed:@"gous"];
            [cell.chooseBtn1 setImage:img forState:UIControlStateNormal];
        }else{
           

            UIImage *img=[UIImage imageNamed:@"quans"];
            [cell.chooseBtn1 setImage:img forState:UIControlStateNormal];
        
        }
        [cell.contentView addSubview:cell.chooseBtn1];
        
    
        UILabel *lineLabel1=[[UILabel alloc] initWithFrame:CGRectMake(10, labelsize.height+30-0.40, ScreenWidth-20, 0.40)];
        lineLabel1.backgroundColor=qianhuiColor;
        [cell.contentView addSubview:lineLabel1];
          }
    return cell;
}
#pragma mark  -select cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == table_list) {
        
        
//        if ([isAvailable[indexPath.row] isEqualToString:@"Y"]) {
            for (int i=0;  i<planId.count; i++) {
                NSIndexPath *indexPath1 =[NSIndexPath indexPathForRow:i inSection:0 ];
                UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath1];
                SelectedGoodCell *sharecell=(SelectedGoodCell *)cell;
                [sharecell.chooseBtn1 setImage:[UIImage imageNamed:@"quans"] forState:UIControlStateNormal];
                [isCurrent replaceObjectAtIndex:i withObject:@"N"];

            }
            
            UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
            SelectedGoodCell *sharecell=(SelectedGoodCell *)cell;
            [sharecell.chooseBtn1 setImage:[UIImage imageNamed:@"gous"] forState:UIControlStateNormal];
            
            isCurrentPlanId=planId[indexPath.row];
            [isCurrent replaceObjectAtIndex:indexPath.row withObject:@"Y"];

//        }else{
//            
//            UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"提示" message:@"不可选择" delegate:self cancelButtonTitle:nil otherButtonTitles:@"取消", nil];
//            [alertView show];
//            
//        }
        
        
    }
    
    
    
}


-(void)deleteBtnBtn:(NSString *)sender{


    NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
    NSArray*arr=[NSArray arrayWithObject:sender];
    [params setObject:userToken forKey:@"tokenId"];
    [params setObject:arr forKey:@"shopCartIds"];
    NSLog(@"******===%@",params);
    [HttpRequest requestData:@"Business/ShopCart/Remove" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            NSLog(@"******===%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                
                [self getNoSpecDataFromDB];
            }
            else
            {
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
                
            }
            
        }else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
    }];



}
//-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return  UITableViewCellEditingStyleDelete;
//
//}
//- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
//    return YES;
//}
//
//-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return @"删除";
//}
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
//{
////    [self.beginDateArray removeObjectAtIndex:indexPath.row];//从指定索引移除
////    [self.endDateArray removeObjectAtIndex:indexPath.row];//从指定索引移除
////    [self.useLimitAmtArray removeObjectAtIndex:indexPath.row];//从指定索引移除
////    [self.qtyArray removeObjectAtIndex:indexPath.row];//从指定索引移除
////    [self.titleArray removeObjectAtIndex:indexPath.row];//从指定索引移除
////    [self.priceArray  removeObjectAtIndex:indexPath.row];//从指定索引移除
////    [self.couponIdArray removeObjectAtIndex:indexPath.row];//从指定索引移除
////    [self.imageUrlFullArray removeObjectAtIndex:indexPath.row];//从指定索引移除
////    [self.snArray removeObjectAtIndex:indexPath.row];//从指定索引移除
////    [table deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
////    [self requestData];
//    
//}

-(void)setAutoLayout
{
    [_titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.right.equalTo(self.view.mas_right) ;
        make.height.equalTo(@40) ;
        make.top.equalTo(self.view.mas_top).with.offset(64);
    }];
    [_clearBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(self.view.mas_right).with.offset(-10) ;
        make.height.equalTo(@40) ;
        make.width.equalTo(@30) ;
        make.top.equalTo(_titleView.mas_top) ;
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left)  ;
        make.right.equalTo(self.view.mas_right)   ;
        make.bottom.equalTo(self.view.mas_bottom);
        make.top.equalTo(self.view.mas_top).with.offset(48);
    }];
    [_lastView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.right.equalTo(_submitConfirmBtn.mas_left) ;
        make.height.equalTo(@48) ;
        make.bottom.equalTo(self.view.mas_bottom);
        
    }];
    [_submitConfirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right) ;
        make.width.equalTo(@160) ;
        make.height.equalTo(@48) ;
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    [_totalCountView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left) ;
        make.right.equalTo(_submitConfirmBtn.mas_left) ;
        make.height.equalTo(@48) ;
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
}

- (IBAction)clearAllBtnClick:(id)sender {
    
    
    if (headerModelArray.count==0) {
        UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"提示" message:@"没有要删除的商品" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }else{
        UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"提示" message:@"确认要删除全部商品吗？" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",@"取消", nil];
        
        alertView.tag=30000;
        [alertView show];
        
 
    }

}
- (IBAction)confirmBtnClick:(id)sender {
    
    if ([self.backType isEqualToString:@"backType"]) {
//        if ([self.delegate respondsToSelector:@selector(reloadGoodInfoData)]) {
        
            [self.delegate reloadGoodInfoData:self.planIdStr];
        
        
        [self.navigationController popViewControllerAnimated:YES];
    }else{
    
        if ([self.typeString isEqualToString:@"SCANCASHIER"]) {
            
            [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
            NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
            [params setObject:userToken forKey:@"tokenId"];
            [HttpRequest requestData:@"Business/ShopCart/Confirm" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                if (isSuccess) {
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                        [Global hideProgressHUDInternal:self.view];
                        if ([[severDataDict.dataDict objectForKey:@"totalQty"] integerValue]==0) {
                            UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"提示" message:@"您未选择商品" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                            [alertView show];
                            
                       
                        }else{
                            OrderExtAddViewController *shouyinVC=[[OrderExtAddViewController alloc] init];//2.0{9个参数 少2个}
                            shouyinVC.dataDictionary=severDataDict.dataDict;
                            shouyinVC.saveTypeStr=_typeString;
                            shouyinVC.orderType=@"order";
                            shouyinVC.OrderSat=@"Order/Add";
                            shouyinVC.memberDict=self.memberDict;
                            [self.navigationController pushViewController:shouyinVC animated:YES];

                        }

                       
                    }
                    else
                    {
                        [Global hideProgressHUDInternal:self.view];
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        [Global showTextHudSub:requestResultStr view:self.view];
                        
                    }
                    
                }else
                {
                    [Global hideProgressHUDInternal:self.view];
                    [Global showTextHudSub:severDataDict.resultStr view:self.view];
                }
            }];
            

            
            
            
}
    else
    {
        UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"提示" message:@"您未选择商品" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    
    }
}

-(void)setNavigation
{
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden=NO;
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UILabel* titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0,40, 23)];
    titleLabel.text=@"已选商品";
    titleLabel.font=[UIFont systemFontOfSize: 17];
    self.navigationItem.titleView=titleLabel;
    self.navigationController.navigationBar.barStyle =UIBaselineAdjustmentNone ;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
   
}

-(void)BackAction:(UIButton *)sender{
   
    [self.delegate reloadGoodInfoData:self.planIdStr];
 

    [self.navigationController popViewControllerAnimated:YES];
}
- (void)showAlertMessage:(NSString *)msg
{
    _alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [_alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:0.5f];
}
- (void)hideAlert
{
    if (_alt != nil)
    {
        [_alt dismissWithClickedButtonIndex:0 animated:YES];
        _alt = nil;
    }
}

@end
